package com.dingding.order.core.publish.biz.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dto.AbstractResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.UserTaxiOrdert;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.GetDistanceUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.dto.CalculatDistanceDTO;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.order.core.publish.biz.IPublishTaxiOrderService;
import com.dingding.order.core.publish.dao.IPublishTaxiOrderDao;
import com.dingding.order.dto.publish.taxi.PublishTaxiOrderStatus;
import com.dingding.order.dto.publish.taxi.ReqPublishTaixOrder;
import com.dingding.order.dto.publish.taxi.ResPublishTaixOrder;

/**
 * @Description: 发布出租车订单service
 * @author fengshuonan
 * @date 2016年7月1日 上午11:10:25
 * @version 叮叮搭车
 */
@Component("publishTaxiOrderService")
public class PublishTaxiOrderServiceImpl extends AbstractResponse<ResPublishTaixOrder,ReqPublishTaixOrder> implements IPublishTaxiOrderService{

	private Logger log = Logger.getLogger(this.getClass());
	
	@Resource(name = "publishTaxiOrderDao")
	private IPublishTaxiOrderDao publishTaxiOrderDao;
	
	@Resource(name = "queueFacade")
	private IQueueFacade queueFacade;
	
	/**
	 * @Description: 发布出租车订单
	 * @param reqReleaseOrder 发布订单请求Bean
	 * @author fengshuonan
	 * @return String 返回类型
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String publishTaxiOrder(String requestData) {
		
		ResponseEntity<ResPublishTaixOrder> responseEntity = new ResponseEntity<ResPublishTaixOrder>();
		
		ReqPublishTaixOrder reqPublishTaixOrder = super.parseRequestJson(requestData);
		
		//验证参数是否为空
		if(!super.validateParam(responseEntity,reqPublishTaixOrder)){
			return super.responseBeanToJson(responseEntity);
		}
		
		// 补充发布出租车订单请求参数
		completionParam(reqPublishTaixOrder);
		
		//判断乘客是否存在未完成的出租车单,如果有未完成的出租车单则不能发单
		if(this.publishTaxiOrderDao.haveUnfinishedTaxiOrder(reqPublishTaixOrder.getPlaceOrderUserId())){
			responseEntity.setCode(PublishTaxiOrderStatus.HAVE_UN_FINISHED_TAXI_ORDER.getCode());
			responseEntity.setErrorMessage(PublishTaxiOrderStatus.HAVE_UN_FINISHED_TAXI_ORDER.getMessage());
			responseEntity.setPromptMessage(PublishTaxiOrderStatus.HAVE_UN_FINISHED_TAXI_ORDER.getMessage());
			return super.responseBeanToJson(responseEntity);
		}
		
		//乘客下单
		UserTaxiOrdert order = this.generateCustomerTaxiOrder(reqPublishTaixOrder, responseEntity);
		if(order == null){
			return super.responseBeanToJson(responseEntity);
		}
		
		//封装返回结果
		ResPublishTaixOrder resPublishTaixOrder = createResult(order);
		responseEntity.setResponseBody(resPublishTaixOrder);
		
		//推送订单给附近的司机
		this.queueFacade.addTaxiOrderToQueue(order);
		
		return super.responseBeanToJson(responseEntity);
	}

	/**
	 * 
	 * @Title: completionParam 
	 * @Description: 补全发布出租车订单请求参数
	 * @param reqPublishTaixOrder 
	 * @author YHQ 
	 * @since V2.5.6
	 * @return ReqPublishTaixOrder    返回类型
	 * 
	 */
	public ReqPublishTaixOrder completionParam(ReqPublishTaixOrder reqPublishTaixOrder){
		
		// 计算里程与获取城市
		CalculatDistanceDTO calculatDistanceDTO = GetDistanceUtil.getSingleDistance(reqPublishTaixOrder.getStartLongitude(),
				reqPublishTaixOrder.getStartLatitude(), reqPublishTaixOrder.getEndLongitude(),
				reqPublishTaixOrder.getEndLatitude());
		
		if(reqPublishTaixOrder == null || calculatDistanceDTO == null){
			return null;
		}
		
		// 下单城市
		if(ToolUtil.isBlank(reqPublishTaixOrder.getPayCity())){
			reqPublishTaixOrder.setPayCity(calculatDistanceDTO.getCityName());
		}
		
		// 人数
		if(reqPublishTaixOrder.getNumber() == null){
			reqPublishTaixOrder.setNumber(0);
		}
		
		// 距离
		if(reqPublishTaixOrder.getDistance() == null){
			reqPublishTaixOrder.setDistance(calculatDistanceDTO.getDistance());
		}
		
		return reqPublishTaixOrder;
	}
	
	/**
	 * @Description:生成乘客订单
	 * @author fengshuonan
	 * @return int 状态码
	 */
	private UserTaxiOrdert generateCustomerTaxiOrder(ReqPublishTaixOrder reqPublishTaixOrder, ResponseEntity<ResPublishTaixOrder> response){
		
		UserTaxiOrdert userTaxiOrdert = new UserTaxiOrdert();
		
		//拷贝请求bean中的所有属性，除了payCity下单城市，因为userTaxiOrdert中属性为placeOrderCity
		BeanUtils.copyProperties(reqPublishTaixOrder, userTaxiOrdert);
		
		//生成订单id
		userTaxiOrdert.setTaxiOrdertId(ToolUtil.getUid());
		
		//设置下单城市
		userTaxiOrdert.setPlaceOrderCity(reqPublishTaixOrder.getPayCity());
		
		//设置出发时间为当前服务器时间
		userTaxiOrdert.setSetOutTime(new Date());
		
		//设置下单时间
		userTaxiOrdert.setCreateTime(new Date());
		
		//设置下单类型（1:司机下单 2:乘客下单）
		userTaxiOrdert.setOrderType(2);
		
		//设置订单状态
		userTaxiOrdert.setOrderStatus(1);
		
		try {
			this.publishTaxiOrderDao.save(userTaxiOrdert);
			return userTaxiOrdert;
		} catch (Exception e) {
			log.error("出租车下单生成订单出错！PublishTaxiOrderServiceImpl : generateCustomerTaxiOrder()",e);
			response.setCode(PublishTaxiOrderStatus.GENERATE_TAXI_ORDER_ERROR.getCode());
			response.setErrorMessage(PublishTaxiOrderStatus.GENERATE_TAXI_ORDER_ERROR.getMessage());
			return null;
		}
	}
	
	/**
	 * @Description: 封装发布出租车订单结果bean
	 * @author fengshuonan
	 * @return ResPublishTaixOrder 发布出租车订单的响应bean
	 * 
	 */
	private ResPublishTaixOrder createResult(UserTaxiOrdert order){
		
		//创建返回结果的封装
		ResPublishTaixOrder resPublishTaixOrder = new ResPublishTaixOrder();
		
		//设置订单id
		resPublishTaixOrder.setOid(order.getTaxiOrdertId());
		
		//设置出发时间
		resPublishTaixOrder.setOutTime(order.getSetOutTime());
		
		//设置提示标语
		resPublishTaixOrder.setTitle(DateFormatUtil.getMMddEHHss(order.getSetOutTime()));
	
		return resPublishTaixOrder;
	}
}
